<template>
    <div class="editor-operate">
        <!-- 背景区 -->
        <!-- <div class="editor-operate-background" @mousedown="onSelect($event)"></div> -->
        <div class="editor-operate-background" @mousedown="onMousedown($event, 'select')"
             @touchstart="onMousedown($event, 'select')"></div>

        <div class="editor-platen-other" v-for="(err, idx) in dstOtherError" :key="idx" :style="err.layerStyle">
            <span :style="err.dstStyle"></span>
        </div>

        <!-- 滑动区 -->
        <div class="editor-operate-dragger" :style="operateStyle" v-if="activeLayer" :status="operateLayerStatus"
             :type="activePiece.type">

            <template v-if="activePiece.type == 2">
                <!-- <div class="editor-platen-move"></div> -->
                <svg-icon v-if="!zoom" name="design-move" class="design-platen-move"
                          @mousedown.native="onMousedown($event, 'platen-move')"
                          @touchstart.native="onMousedown($event, 'platen-move')" />
                <div class="editor-platen-dst" :style="dstStyle">
                    <div @mousedown="onMousedown($event, 'dst-move')" @touchstart="onMousedown($event, 'dst-move')"
                         class="design-dst-move"></div>
                    <svg-icon name="design-delete" class="design-dst-delete" @click.native="removeDst(activeDst)"
                              :style="operateIconStyle" />
                    <svg viewBox="0 0 24 24" @mousedown="onMousedown($event, 'dst-rotate')"
                         @touchstart="onMousedown($event, 'dst-rotate')" class="design-dst-rotate"
                         :style="operateIconStyle">
                        <path d="M18,8.264625 L15.5625,5 L13.125,8.264625 L14.74675,8.264625 C14.7150625,11.8371875 11.813625,14.7345625 8.25,14.7345625 L8.25,13.10225 L5,15.551125 L8.25,18 L8.25,16.366875 C12.7098125,16.366875 16.33925,12.7374375 16.37175,8.264625 L18,8.264625 Z"
                              stroke="none"></path>
                    </svg>
                </div>

            </template>

            <template v-else>
                <div @mousedown="onMousedown($event, 'move')" @touchstart="onMousedown($event, 'move')"
                     class="operate-move"></div>

                <button @mousedown="onMousedown($event, 'zoom')" @touchstart="onMousedown($event, 'zoom')">
                    <svg viewBox="0 0 24 24">
                        <g transform="translate(6, 6)" stroke="none">
                            <polygon points="7.713 0.585 11.16 4.032 11.745 0"></polygon>
                            <polygon points="0 11.745 4.032 11.16 0.585 7.713"></polygon>
                            <polygon points="2.4466 10.4458 1.2996 9.2988 9.1556 1.4428 10.3026 2.5898"></polygon>
                        </g>
                    </svg>
                </button>
                <button @mousedown="onMousedown($event, 'rotate')" @touchstart="onMousedown($event, 'rotate')"
                        :style="operateIconStyle">
                    <svg viewBox="0 0 24 24">
                        <path d="M18,8.264625 L15.5625,5 L13.125,8.264625 L14.74675,8.264625 C14.7150625,11.8371875 11.813625,14.7345625 8.25,14.7345625 L8.25,13.10225 L5,15.551125 L8.25,18 L8.25,16.366875 C12.7098125,16.366875 16.33925,12.7374375 16.37175,8.264625 L18,8.264625 Z"
                              stroke="none"></path>
                    </svg>
                </button>
                <button @click="removeLayer(activeLayer)" :style="operateIconStyle">
                    <svg-icon name="design-delete" />
                </button>

            </template>

        </div>
    </div>
</template>

<script>
import DesignUtils from '@/utils/DesignUtils.js';
import { mapGetters, mapState } from "vuex";

export default {
    props: {
        zoom: { type: Boolean, default: false },
        activeSurface: { type: Object, default: null },
        activePiece: { type: Object, default: null },
        activeLayer: { type: Object, default: null },
        activeDst: { type: Object, default: null },
        lock: { type: Array, default: () => [] },// 锁定的图层不可选中, 规则：canvas_name + layer.id
    },
    data () {
        return {
            mouse_up: null,
        };
    },

    computed: {
        ...mapState("designer", { oversizeDst: "oversize_dst", overlapDst: "overlap_dst" }),
        ...mapGetters("designer", {
            lastActiveLayer: 'getLastActiveLayer',
        }),

        // 渲染器
        // 操作区
        operateStyle () {

            if (this.activeLayer) {

                // 要计算二次旋转角度
                let layer = this.activeLayer;
                let piece = this.activePiece;

                // 获取元素中间真实位置
                let x1 = piece.canvas_left + layer.x + 0.5 * layer.w;
                let y1 = piece.canvas_top + layer.y + 0.5 * layer.h;
                let x2 = piece.canvas_left + 0.5 * piece.canvas_width;
                let y2 = piece.canvas_top + 0.5 * piece.canvas_height;

                let point = DesignUtils.pointRotate(x1, y1, -piece.canvas_rotate, x2, y2)

                let width = layer.w / piece.outer_width;
                let height = layer.h / piece.outer_height;
                let left = (point.x - 0.5 * layer.w) / piece.outer_width;
                let top = (point.y - 0.5 * layer.h) / piece.outer_width;
                let rotate = piece.canvas_rotate + layer.rotate;


                return {
                    width: 100 * width + '%',
                    height: 100 * height + '%',
                    left: 100 * left + '%',
                    top: 100 * top + '%',
                    transform: `rotate(${rotate}deg)`,
                }

            } else {
                return {}
            }
        },

        dstStyle () {
            //  内容区
            if (this.activeLayer && this.activeDst) {
                let rotate = this.activeDst.rotate

                return {
                    left: 100 * this.activeDst.x / this.activeLayer.w + '%',
                    top: 100 * this.activeDst.y / this.activeLayer.h + '%',
                    width: 100 * this.activeDst.w / this.activeLayer.w + '%',
                    height: 100 * this.activeDst.h / this.activeLayer.h + '%',
                    transform: `rotate(${rotate}deg)`,
                }


            } else {
                return { display: 'none' }
            }
        },

        // 当有错误时，把其他版带显示出来
        dstOtherError () {

            if (this.activePiece && this.activePiece.type == 2) {
                const list = this.oversizeDst.length > 0 ? this.oversizeDst : this.overlapDst;
                const filter = list.filter(i => i.dst != this.activeDst && i.piece.surface_name == this.activePiece.surface_name)

                return filter.map(item => {
                    const dst = item.dst
                    const layer = item.layer
                    const piece = item.piece;


                    // 获取元素中间真实位置
                    let x1 = piece.canvas_left + layer.x + 0.5 * layer.w;
                    let y1 = piece.canvas_top + layer.y + 0.5 * layer.h;
                    let x2 = piece.canvas_left + 0.5 * piece.canvas_width;
                    let y2 = piece.canvas_top + 0.5 * piece.canvas_height;

                    let point = DesignUtils.pointRotate(x1, y1, -piece.canvas_rotate, x2, y2)

                    let width = layer.w / piece.outer_width;
                    let height = layer.h / piece.outer_height;
                    let left = (point.x - 0.5 * layer.w) / piece.outer_width;
                    let top = (point.y - 0.5 * layer.h) / piece.outer_width;
                    let rotate = piece.canvas_rotate + layer.rotate;


                    return {
                        layerStyle: {
                            width: 100 * width + '%',
                            height: 100 * height + '%',
                            left: 100 * left + '%',
                            top: 100 * top + '%',
                            transform: `rotate(${rotate}deg)`,
                        },
                        dstStyle: {
                            left: 100 * dst.x / layer.w + '%',
                            top: 100 * dst.y / layer.h + '%',
                            width: 100 * dst.w / layer.w + '%',
                            height: 100 * dst.h / layer.h + '%',
                            transform: `rotate(${dst.rotate}deg)`,
                        }
                    }


                })

            } else {
                return []
            }

        },

        operateIconStyle () {
            let layer_rotate = this.activeLayer.rotate;
            let piece_rotate = this.activePiece.canvas_rotate;
            let dst_rotate = this.activeDst ? this.activeDst.rotate : 0;

            return { transform: `rotate(${-dst_rotate - layer_rotate - piece_rotate}deg)` }
        },

        operateLayerStatus () {

            if (!this.activePiece) {
                // 没有选中设计面
                return 'high';
            } else if (!this.activeLayer) {
                // 没有选中图层
                return 'high';
            } else if (this.activePiece.type == 2) {
                // 刺绣
                if (this.oversizeDst.find(i => i.dst == this.activeDst)) {
                    return 'low'
                } else if (this.overlapDst.find(i => i.dst == this.activeDst)) {
                    return 'low'
                } else {
                    return 'high'
                }

            } else if (this.activeLayer.type == 'image') {

                const now_dpi = 300; // 当前dpi
                const piece = this.activePiece;
                const layer = this.activeLayer;

                const scale = Math.max(piece.real_width / piece.canvas_width, piece.real_height / piece.canvas_height);
                const realW = layer.w * scale;
                const realH = layer.h * scale;
                const imageDpi = Math.min(layer.cutW / realW, layer.cutW / realW) * now_dpi;

                if (imageDpi >= 150) {
                    return 'high';
                } else if (imageDpi < 150 && imageDpi >= 75) {
                    return 'middle';
                } else if (imageDpi < 75) {
                    return 'low';
                }
            } else {
                return 'high';
            }
        }

    },

    methods: {

        // 获取缩放大小
        getScale () {
            if (this.$el && this.activePiece) {
                let warper = this.$el.getBoundingClientRect();
                let piece = this.activePiece;
                let offset = 0; // 和边框的间距
                let warperWidth = warper.width - offset * 2;
                let warperHeight = warper.height - offset * 2;
                let pieceWidth = piece.outer_width;
                let pieceHeight = piece.outer_height;

                return Math.min(warperWidth / pieceWidth, warperHeight / pieceHeight) || 1;
            } else {
                return 1;
            }
        },

        // 图片裁剪样式
        getImageCropStyle (item) {

            // cutX,cutY,cutW,cutH 表示相对图片裁剪的的像素
            // 图片裁剪cutX、cutY必定为正数
            // 业务逻辑为，把图片按cut裁剪后，拉伸放到容器中

            let w = item.image_w * item.w / item.cutW;
            let h = item.image_h * item.h / item.cutH;
            let x = -item.cutX * item.w / item.cutW;
            let y = -item.cutY * item.h / item.cutH;

            return {
                width: 100 * w / item.w + '%',
                height: 100 * h / item.h + '%',
                left: 100 * x / item.w + '%',
                top: 100 * y / item.h + '%',
            }
        },

        removeLayer (layer) {
            this.$emit('global:DESIGN_REMOVE_LAYER', layer);
        },

        removeDst (dst) {
            this.$emit('global:DESIGN_REMOVE_DST', { layer: this.activeLayer, dst: dst });
        },


        // 鼠标按下选中时
        onSelect (event, penetrate) {

            const outer = this.$el.getBoundingClientRect();
            const surface = this.activeSurface || {};
            const piece = this.activePiece || {};
            const pieces = (surface.pieces || []).filter(i => penetrate || i.type == piece.type);


            const touch = (event.targetTouches || [])[0];
            const clientX = touch ? touch.clientX : event.clientX;
            const clientY = touch ? touch.clientY : event.clientY;

            const percentX = (clientX - outer.left) / outer.width;  // 点击位置相对容器距离百分比
            const percentY = (clientY - outer.top) / outer.height;

            // 鼠标点击位置，相对于容器
            const x1 = percentX * surface.outer_width;
            const y1 = percentY * surface.outer_height;

            // 点击在里面的元素
            const inside = [];

            // 循环
            pieces.map(piece => {

                // 设计区中点的位置
                const pcx = piece.canvas_left + 0.5 * piece.canvas_width;
                const pcy = piece.canvas_top + 0.5 * piece.canvas_height;

                // 鼠标坐标相对于设计区中点经过旋转后的位置，相对于设计区坐标
                const θ1 = (360 - piece.canvas_rotate) * Math.PI / 180;
                const x2 = (x1 - pcx) * Math.cos(θ1) - (y1 - pcy) * Math.sin(θ1) + pcx - piece.canvas_left;
                const y2 = (x1 - pcx) * Math.sin(θ1) + (y1 - pcy) * Math.cos(θ1) + pcy - piece.canvas_top;

                const inpieceX = x2 >= 0 && x2 <= piece.canvas_width;
                const inpieceY = y2 >= 0 && y2 <= piece.canvas_height;

                // 在设计区中，再计算是否在每个图层里面
                inpieceX && inpieceY && piece.layers.map(layer => {

                    // 图层中点的位置
                    const lcx = layer.x + 0.5 * layer.w;
                    const lcy = layer.y + 0.5 * layer.h;

                    const θ2 = (360 - layer.rotate) * Math.PI / 180;
                    const x3 = (x2 - lcx) * Math.cos(θ2) - (y2 - lcy) * Math.sin(θ2) + lcx;
                    const y3 = (x2 - lcx) * Math.sin(θ2) + (y2 - lcy) * Math.cos(θ2) + lcy;

                    const inlayerX = 2 * Math.abs(x3 - lcx) <= layer.w;
                    const inlayerY = 2 * Math.abs(y3 - lcy) <= layer.h;
                    const layerId = piece.canvas_name + layer.id;
                    const isLock = this.lock.indexOf(layerId) >= 0;


                    if (inlayerX && inlayerY && !isLock) {
                        const dsts = []
                        if (piece.type == 2) {

                            layer.dists.map(dst => {

                                // 图层中点的位置
                                const dcx = x3 - lcx - (dst.x + 0.5 * dst.w - 0.5 * layer.w);
                                const dcy = y3 - lcy - (dst.y + 0.5 * dst.h - 0.5 * layer.h);

                                const rotation = DesignUtils.coordinateRotation(dcx, dcy, 0, 0, -dst.rotate)
                                const inDstX = 2 * Math.abs(rotation.x) <= dst.w;
                                const inDstY = 2 * Math.abs(rotation.y) <= dst.h;

                                inDstX && inDstY && dsts.push(dst)
                            })

                            if (!penetrate || dsts.length > 0) {
                                // 穿透的，必须是选中版带
                                inside.push({ layer: layer, piece: piece, dst: dsts[dsts.length - 1] });
                            }

                        } else {
                            inside.push({ layer: layer, piece: piece, dst: null });
                        }


                    }

                });
            });


            // 选中
            if (inside.length > 0) {
                // 其他设计区内的，默认是最后一条
                let other = inside[inside.length - 1];
                // 当前设计区内的
                let current = other && other.piece == this.activePiece ? other : null;

                if (penetrate) {
                    // 穿透
                    return other
                } else if (this.activePiece && this.activePiece.type == 2) {
                    // 刺绣
                    const activeLayer = this.activeLayer || this.lastActiveLayer
                    const piece = current || (this.zoom ? null : other)
                    const layer = piece && piece.layer == activeLayer ? piece : this.zoom ? null : other;

                    if (this.zoom) {
                        // 放大时，不切换绣框
                        return layer && layer.dst ? layer : inside.find(i => i.layer == activeLayer && i.dst)
                    } else {
                        return layer && layer.dst ? layer : inside.find(i => i.dst)
                    }

                } else {
                    // 缩放状态下，只能选中当前片区的图层
                    return current || (this.zoom ? null : other)
                }

            } else {
                return null;
            }
        },

        // 鼠标按下
        onMousedown (event, action) {

            event.preventDefault();
            event.stopPropagation();

            let dst = this.activeDst;
            let layer = this.activeLayer;
            let piece = this.activePiece;
            const touch = (event.targetTouches || [])[0];
            const clientX = touch ? touch.clientX : event.clientX;
            const clientY = touch ? touch.clientY : event.clientY;

            if (action == 'move' || action == 'select') {

                let select = this.onSelect(event) || {};
                // let selectLayer = select.layer

                if (action == 'select') {

                    action = 'move';
                    layer = select.layer;

                    if (select.dst) {
                        action = 'dst-move'
                        dst = select.dst;
                    } else if (piece.type == 2) {
                        // 绣框
                        action = ''
                    } else {
                        dst = null;
                    }

                } else {
                    layer = select.layer || layer;
                }

                // 切换设计面
                if (this.activeLayer != layer) {

                    this.$emit('selectLayer', layer);
                    piece = this.activeSurface.pieces.filter(i => i.layers.indexOf(layer) >= 0)[0];
                }

                // 刺绣选中版带
                if (piece && piece.type == 2 && layer && this.activeDst != dst) {
                    this.$store.commit("designer/SET_ACTIVE_DST_INDEX", layer.dists.indexOf(dst));
                } else {
                    this.$store.commit("designer/SET_ACTIVE_DST_INDEX", -1);
                }
            }

            if (layer && /move|zoom|rotate|remove|platen-move|dst-move|dst-rotate/.test(action)) {

                let mouse = {};
                let scale = this.getScale();

                let outer = this.$el.getBoundingClientRect();
                let left = outer.width * (layer.x + piece.canvas_left) / piece.outer_width;
                let top = outer.height * (layer.y + piece.canvas_top) / piece.outer_height;
                let width = outer.width * layer.w / piece.outer_width;
                let height = outer.height * layer.h / piece.outer_height;

                let dstX = dst ? (dst.x + 0.5 * dst.w - 0.5 * layer.w) * outer.width / piece.outer_width : 0;
                let dstY = dst ? (dst.y + 0.5 * dst.h - 0.5 * layer.h) * outer.height / piece.outer_height : 0;

                mouse.scale = scale;
                mouse.action = action;
                mouse.cache = JSON.parse(JSON.stringify(dst && /dst-move|dst-rotate/.test(action) ? dst : layer));
                mouse.piece = piece;
                mouse.layer = layer;
                mouse.dst = dst;
                mouse.start = new Date().getTime();
                mouse.clientX = clientX;
                mouse.clientY = clientY;
                mouse.centerX = outer.left + left + 0.5 * width + dstX;
                mouse.centerY = outer.top + top + 0.5 * height + dstY;
                mouse.offsetX = 0;
                mouse.offsetY = 0;

                // 一半的对角线长度
                // mouse.diagonal = Math.sqrt(Math.pow(mouse.cache.w, 2)+Math.pow(mouse.cache.h, 2)) / 2;

                this.mouse = mouse;

            }
        },

        // 鼠标移动
        // 要做节流处理，防止频繁操作
        onMousemove (event) {

            if (!this.mouse) { return; }

            event.preventDefault();
            event.stopPropagation();

            const mouse = this.mouse;
            const scale = this.mouse.scale;
            const layer = this.mouse.layer;
            const dst = this.mouse.dst;
            const piece = this.mouse.piece;
            const touch = (event.targetTouches || [])[0];
            const clientX = touch ? touch.clientX : event.clientX;
            const clientY = touch ? touch.clientY : event.clientY;
            const offsetX = clientX - mouse.clientX;
            const offsetY = clientY - mouse.clientY;


            this.mouse.offsetX = offsetX;
            this.mouse.offsetY = offsetY;


            if (mouse.action == 'dst-move') {

                const θ = (360 - piece.canvas_rotate) * Math.PI / 180;
                const toX = offsetX * Math.cos(θ) - offsetY * Math.sin(θ);
                const toY = offsetX * Math.sin(θ) + offsetY * Math.cos(θ);

                // 移动
                const x = Math.round(mouse.cache.x + toX / scale);
                const y = Math.round(mouse.cache.y + toY / scale);

                // 真实宽高
                const real = DesignUtils.rectRealSize(dst.w, dst.h, dst.rotate)
                // 移动限制
                const range = {
                    minX: 0.5 * real.width - 0.5 * dst.w,
                    maxX: layer.w - 0.5 * real.width - 0.5 * dst.w,
                    minY: 0.5 * real.height - 0.5 * dst.h,
                    maxY: layer.h - 0.5 * real.height - 0.5 * dst.h
                }

                const change = {
                    x: Math.max(range.minX, Math.min(range.maxX, x)),
                    y: Math.max(range.minY, Math.min(range.maxY, y)),
                }
                this.$emit('updateDst', change);

            } else if (mouse.action == 'dst-rotate') {

                // 旋转

                // 中间点
                const center = { x: mouse.centerX, y: mouse.centerY }

                // 右下顶点与中点的向量夹角
                // 鼠标点击时和中心点的角度
                const rotate1 = Math.atan2(mouse.clientY - center.y, mouse.clientX - center.x) * 180 / Math.PI;

                // 鼠标旋转后，和中心点的角度
                const rotate2 = Math.atan2(clientY - center.y, clientX - center.x) * 180 / Math.PI;

                // 旋转角度=鼠标角度偏差+原来的角度
                const rotate = mouse.cache.rotate + rotate2 - rotate1;

                // 范围是-180至180
                const change = {
                    rotate: Math.round(rotate + 360) % 360
                }
                this.$emit('updateDst', change);


            } else if (mouse.action == 'platen-move') {


                const θ = (360 - piece.canvas_rotate) * Math.PI / 180;
                const toX = offsetX * Math.cos(θ) - offsetY * Math.sin(θ);
                const toY = offsetX * Math.sin(θ) + offsetY * Math.cos(θ);

                // 移动
                const x = Math.round(mouse.cache.x + toX / scale);
                const y = Math.round(mouse.cache.y + toY / scale);


                const range = {
                    x: Math.max(0, Math.min(piece.canvas_width - layer.w, x)),
                    y: Math.max(0, Math.min(piece.canvas_height - layer.h, y))
                }

                this.$emit('updateLayer', range);

            } else if (mouse.action == 'move') {

                const θ = (360 - piece.canvas_rotate) * Math.PI / 180;
                const toX = offsetX * Math.cos(θ) - offsetY * Math.sin(θ);
                const toY = offsetX * Math.sin(θ) + offsetY * Math.cos(θ);

                // 移动
                const x = Math.round(mouse.cache.x + toX / scale);
                const y = Math.round(mouse.cache.y + toY / scale);

                // const size = DesignUtils.rectRealSize(layer.w, layer.h, mouse.cache.rotate)
                // const minX = - 0.5 * layer.w - 0.5 * size.width;
                // const maxX = piece.canvas_width + 0.5 * size.width - 0.5 * layer.w;
                // const minY = - 0.5 * mouse.cache.h - 0.5 * size.height;
                // const maxY = piece.canvas_height + 0.5 * size.height - 0.5 * layer.h;

                // 范围
                const rect1 = {
                    x: 10 / mouse.scale,
                    y: 10 / mouse.scale,
                    w: piece.canvas_width - 20 / mouse.scale,
                    h: piece.canvas_height - 20 / mouse.scale,
                    r: 0,
                }
                const rect2 = {
                    x: x,
                    y: y,
                    w: layer.w,
                    h: layer.h,
                    r: layer.rotate,
                }

                const edge = DesignUtils.rectIsIntersect(rect1, rect2);
                const change = {
                    x: edge.x,
                    y: edge.y,
                };
                this.$emit('updateLayer', change);

            } else if (mouse.action == 'zoom') {
                // 缩放
                // 基于中心放大
                // 右上角顶点角度

                // 鼠标拖移弧度
                const angle1 = Math.atan2(offsetY, offsetX);
                // 右上角的角度
                const angle2 = Math.atan2(-mouse.cache.h, mouse.cache.w);
                // 右上角真实角度
                const angle3 = angle2 + (mouse.cache.rotate + piece.canvas_rotate) * Math.PI / 180;
                // 右上角位移变量
                const length = Math.sqrt(Math.pow(offsetY, 2) + Math.pow(offsetX, 2)) * Math.cos(angle3 - angle1);
                // 对角线长度
                const diagonal = Math.sqrt(Math.pow(mouse.cache.w, 2) + Math.pow(mouse.cache.h, 2)) / 2;
                // 最小比例
                const minsize = Math.max(1 / mouse.cache.w, 1 / mouse.cache.h);
                // 长度变化
                const percent = Math.max(minsize, 1 + length / scale / diagonal);
                const change = {}

                change.w = mouse.cache.w * percent;
                change.h = mouse.cache.h * percent;
                change.x = mouse.cache.x + (mouse.cache.w - change.w) / 2;
                change.y = mouse.cache.y + (mouse.cache.h - change.h) / 2;

                // 文字，改字号
                if (layer.type == 'text') {
                    change.font_size = mouse.cache.font_size * percent;
                }

                this.$emit('updateLayer', change);

            } else if (mouse.action == 'rotate') {
                // 旋转
                // 右下顶点与中点的向量夹角
                // 鼠标点击时和中心点的角度
                const rotate1 = Math.atan2(mouse.clientY - mouse.centerY, mouse.clientX - mouse.centerX) * 180 / Math.PI;

                // 鼠标旋转后，和中心点的角度
                const rotate2 = Math.atan2(clientY - mouse.centerY, clientX - mouse.centerX) * 180 / Math.PI;

                // 旋转角度=鼠标角度偏差+原来的角度
                const rotate = mouse.cache.rotate + rotate2 - rotate1;

                // 范围是-180至180
                const change = {
                    rotate: Math.round(rotate + 360) % 360
                }
                this.$emit('updateLayer', change);
            }
        },

        // 鼠标弹起
        onMouseup (event) {
            if (this.mouse) {
                event.preventDefault();
                event.stopPropagation();
                this.mouse = null;
                this.$emit('global:DESIGN_NOTIFY_CHECK')
                this.$emit('global:DESIGN_NOTIFY_LIMIT')
            }


            // 双击
            if (event.target.closest('.editor-operate') == this.$el && this.getDblclick(event)) {
                const select = this.onSelect(event, true)
                if (!select) {
                    // 没有选中，都不管
                } else if (select.piece.type == 2 && select.layer == this.activeLayer) {
                    // 相同的，放大
                    this.$emit('global:DESIGN_EMB_DBLCLICK', {})
                } else {
                    // 不同的，切换
                    if (select.piece.type == 2) {
                        this.$emit('selectLayer', select.layer);
                        select.dst && this.$store.commit("designer/SET_ACTIVE_DST_INDEX", select.layer.dists.indexOf(select.dst));
                    } else {
                        this.activeLayer != select.layer && this.$emit('selectLayer', select.layer);
                    }
                }
            }

        },

        getDblclick (event) {

            const touch = (event.targetTouches || [])[0];
            const clientX = touch ? touch.clientX : event.clientX;
            const clientY = touch ? touch.clientY : event.clientY;
            const time = new Date().getTime()

            if (this.mouse_up && (time - this.mouse_up.time < 300) && Math.abs(clientX - this.mouse_up.x) < 10 && Math.abs(clientY - this.mouse_up.y) < 10) {
                this.mouse_up = null
                return true
            } else {
                this.mouse_up = { time: time, x: clientX, y: clientY }
                return false;
            }
        },

        // 键盘弹起
        onKeyup (event) {
            if (!this.activeLayer) {
                // 没有选中，不管
            } else if (!(!document.activeElement || document.activeElement == document.body || document.activeElement.tagName == 'BUTTON')) {
                // 其他位置输入框
            } else {

                const scale = this.getScale();
                const piece = this.activePiece;
                const layer = this.activeLayer;
                const dst = this.activeDst;
                const offset = 10 / scale;
                const target = dst || layer;

                const move = {}
                // 8 回退 46 Delete
                if (event.keyCode == 8 || event.keyCode == 46) {
                    // 删除
                    if (dst) {
                        this.removeDst(target)
                    } else if (piece.type == 2) {
                        // 刺绣，如果只有一个版带就删除
                        layer.dists && layer.dists.length == 1 && this.removeLayer(target)
                    } else {
                        this.removeLayer(target)
                    }
                } else if (event.keyCode == 38) {
                    // 上移
                    move.y = Math.round(target.y - offset)
                } else if (event.keyCode == 40) {
                    // 下移
                    move.y = Math.round(target.y + offset)
                } else if (event.keyCode == 37) {
                    // 左移
                    move.x = Math.round(target.x - offset)
                } else if (event.keyCode == 39) {
                    // 右移
                    move.x = Math.round(target.x + offset)
                }
                dst ? this.toDstMoveChange(target, move) : this.toLayerMoveChange(target, move);
            }
        },
        toDstMoveChange (dst, move) {
            const layer = this.activeLayer;
            // 移动
            const x = typeof move.x == 'undefined' ? dst.x : move.x;
            const y = typeof move.y == 'undefined' ? dst.y : move.y;

            // 真实宽高
            const real = DesignUtils.rectRealSize(dst.w, dst.h, dst.rotate)
            // 移动限制
            const range = {
                minX: 0.5 * real.width - 0.5 * dst.w,
                maxX: layer.w - 0.5 * real.width - 0.5 * dst.w,
                minY: 0.5 * real.height - 0.5 * dst.h,
                maxY: layer.h - 0.5 * real.height - 0.5 * dst.h
            }

            const change = {
                x: Math.max(range.minX, Math.min(range.maxX, x)),
                y: Math.max(range.minY, Math.min(range.maxY, y)),
            }
            this.$emit('updateDst', change);
        },
        toLayerMoveChange (layer, move) {
            const piece = this.activePiece;

            // 移动
            const x = move.x || layer.x;
            const y = move.y || layer.y;


            const range = {
                x: Math.max(0, Math.min(piece.canvas_width - layer.w, x)),
                y: Math.max(0, Math.min(piece.canvas_height - layer.h, y))
            }

            this.$emit('updateLayer', range);
        }
    },

    // 创建
    mounted () {
        window.addEventListener('mousemove', this.onMousemove, false); // 鼠标移动
        window.addEventListener('mouseup', this.onMouseup, false); // 鼠标弹起
        window.addEventListener('touchmove', this.onMousemove, { passive: false }); // 鼠标移动
        window.addEventListener('touchend', this.onMouseup, { passive: false }); // 鼠标弹起
        window.addEventListener('keyup', this.onKeyup, false); // 键盘弹起
    },
    // 销毁
    beforeDestroy: function () {
        window.removeEventListener('mousemove', this.onMousemove); // 鼠标移动
        window.removeEventListener('mouseup', this.onMouseup); // 鼠标弹起
        window.removeEventListener('touchmove', this.onMousemove); // 鼠标移动
        window.removeEventListener('touchend', this.onMouseup); // 鼠标弹起
        window.removeEventListener('keyup', this.onKeyup); // 鼠标弹起
    }
};
</script>

<style lang="scss" scoped>
.editor-operate {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    pointer-events: all;
    z-index: 2;
}

.editor-operate-background {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
}

.editor-platen-other {
    position: absolute;
    box-sizing: border-box;
    pointer-events: none;

    span {
        position: absolute;
        left: 0;
        top: 0;
        border: 1px dashed #f44336;
        box-sizing: border-box;
    }
}

.editor-operate-dragger {
    position: absolute;
    box-sizing: border-box;
    pointer-events: none;

    &[type='1']::before {
        content: '';
        position: absolute;
        left: -2px;
        top: -2px;
        width: 4px;
        height: 4px;
        border-radius: 2px;
        background: #23b98f;
    }

    &[type='1']::after {
        content: '';
        position: absolute;
        right: -2px;
        top: -2px;
        width: 4px;
        height: 4px;
        border-radius: 2px;
        background: #23b98f;
    }

    &[type='2']::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        border: 2px solid #555;
    }

    &>.design-platen-move {
        position: absolute;
        right: -22px;
        top: -22px;
        width: 24px;
        height: 24px;
        color: #555;
        pointer-events: all;
        cursor: pointer;

        &:hover {
            color: #000;
        }
    }

    &>.editor-platen-dst {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        box-sizing: border-box;

        &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            border: 1px dashed #23b98f;
        }

        .design-dst-move {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            pointer-events: all;
        }

        &>svg {
            position: absolute;
            width: 24px;
            height: 24px;
            box-sizing: border-box;
            padding: 2px;
            pointer-events: all;
            cursor: pointer;

            &.design-dst-delete {
                background: #f0f0f0;
                border-radius: 20px;
                left: -24px;
                top: -24px;
                color: #5c5c5c;

                &:hover {
                    color: #f44336;
                }
            }

            &.design-dst-rotate {
                left: 100%;
                top: 100%;
                background: #23b98f;
                border-radius: 20px;
                fill: #fff;

                &:hover {
                    background-color: #1b9d79;
                }
            }
        }
    }

    .editor-platen-move {
        position: absolute;
        right: 0;
    }

    &>.operate-move {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        border: 1px dashed #23b98f;
        box-sizing: border-box;
        cursor: move;
        pointer-events: all;

        &::before {
            content: '';
            position: absolute;
            left: -2px;
            bottom: -2px;
            width: 4px;
            height: 4px;
            border-radius: 2px;
            background: #23b98f;
        }

        &::after {
            content: '';
            position: absolute;
            right: -2px;
            bottom: -2px;
            width: 4px;
            height: 4px;
            border-radius: 2px;
            background: #23b98f;
        }
    }

    &[type='1'][status='middle'] {
        &::before {
            background: #edb002;
        }

        &::after {
            background: #edb002;
        }

        .operate-move {
            border-color: #edb002;
        }

        .operate-move::before {
            background: #edb002;
        }

        .operate-move::after {
            background: #edb002;
        }
    }

    &[type='1'][status='low'] {
        &::before {
            background: #f44336;
        }

        &::after {
            background: #f44336;
        }

        .operate-move {
            border-color: #f44336;
        }

        .operate-move::before {
            background: #f44336;
        }

        .operate-move::after {
            background: #f44336;
        }
    }

    &[type='2'][status='low'] .editor-platen-dst {
        &::before {
            border-color: #f44336;
            border-style: solid;
        }
    }

    button {
        position: absolute;
        width: 24px;
        height: 24px;
        line-height: 24px;
        border-radius: 24px;
        left: -24px;
        top: -24px;
        background: #23b98f;
        color: #fff;
        border: none;
        margin: 0;
        padding: 0;
        text-align: center;
        font-size: 18px;
        pointer-events: all;
        box-sizing: border-box;
        padding: 2px;

        svg {
            width: 24px;
            height: 24px;
            fill: #fff;
            stroke: #fff;
        }

        &:hover {
            background: #1b9d79;
        }

        &:nth-child(2) {
            left: auto;
            right: -24px;
        }

        &:nth-child(3) {
            left: auto;
            top: auto;
            bottom: -24px;
            right: -24px;
        }

        &:nth-child(4) {
            background: #f0f0f0;

            svg {
                fill: #5c5c5c;
                stroke: #5c5c5c;
            }

            &:hover {
                background: #f0f0f0;

                svg {
                    fill: #f44336;
                    stroke: #f44336;
                }
            }
        }
    }
}
</style>
